<?php

namespace App\Http\Controllers\Common\Amap;

use App\Http\Controllers\ClientController;
use App\Models\Common\RedisTool;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class GeocodeRegeoController extends ClientController
{

    public function index()
    {
        $all = $this->all;

        $longitude = $all['longitude'];// 经度
        $latitude = $all['latitude'];// 纬度
        $myAmapKey = 'fa0a54dd005e5a014801d63ea73fc9bd';

        // 高德逆地址编码：经纬度转换为省市区
        try {
            $url = "http://restapi.amap.com/v3/geocode/regeo?location=" . $longitude . ',' . $latitude . "&output=json&key=" . $myAmapKey;
            $content = file_get_contents($url);
            $arr = json_decode($content, true);
            if ($arr['status'] !== '1') {
                Log::error('地址解析失败', $arr);
                throw new \Exception('地址解析失败');
            }
            $adcode = $arr['regeocode']['addressComponent']['adcode'];
            $path = DB::table('dict_area')->where('id', '=', $adcode)->value('path');
            if (!$path) Log::error('地址解析失败,没有此地址', $arr);
            $path = explode(',', $path);
            DB::table('lottery_users')->where('we_id', '=', $this->we_id)->update([
                'longitude' => $longitude,
                'latitude' => $latitude,
                'address_province' => $path[0] ?? null,
                'address_city' => $path[1] ?? null,
                'address_district' => $path[2] ?? null,
                'address_updated_at' => date('Y-m-d H:i:s'),
            ]);
            // 刷新redis
            RedisTool::refreshUser($this->we_id);

            return $this->setReturnJson(0, 'success', $arr);
        } catch (\Exception $e) {
            Log::error(GeocodeRegeoController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '地址解析失败');
        }


    }

}
